package com.weiqiao.api.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.api.domain.AppUserApiEntity;
import com.weiqiao.api.domain.BankApiEntity;
import com.weiqiao.api.domain.CardCommodityApiEntity;
import com.weiqiao.api.domain.TeamCommodityApiEntity;
import com.weiqiao.api.domain.vo.CardCommodityApiVO;
import com.weiqiao.api.repository.IAppuserApiRepository;
import com.weiqiao.api.repository.ICardCommodityApiRepository;
import com.weiqiao.api.repository.ITeamCommodityApiRepository;
import com.weiqiao.api.service.ICardCommodityApiService;
import com.weiqiao.utils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ChenYF
 * @Description
 * @Date 2020/7/27 17:08
 */
@Service("CardCommodityApiServiceImpl")
public class CardCommodityApiServiceImpl implements ICardCommodityApiService {

    @Autowired
    private ICardCommodityApiRepository cardCommodityApiRepository;

    @Autowired
    private IAppuserApiRepository appUserApiRepository;

    @Autowired
    private ITeamCommodityApiRepository teamCommodityApiRepository;


    @Override
    public List<CardCommodityApiEntity> findCommoditys(CardCommodityApiVO vo) {
        // 返回结果
        List<CardCommodityApiEntity> commodityList = new ArrayList<>();
        // 获取用户信息
        AppUserApiEntity entity = new AppUserApiEntity();
        if (vo.getUser_id() > 0 && vo.getCompany_id() > 0) {
            String info = appUserApiRepository.getAppUserByFilter(vo.getCompany_id(), new Document("user_id", vo.getUser_id()));
            if (!StringUtil.isBlank(info)) {
                entity = new Gson().fromJson(info, AppUserApiEntity.class);
            }
        }
        // 获取信用卡
        int company_id = vo.getCompany_id();
        // 查询条件拼接
        Document doc = getParam(vo);
        // 分页条件拼接
        int skip = vo.getPage() * vo.getSize();
        Bson sort = new Document("create_date", -1);
        List<String> list = cardCommodityApiRepository.findPageList(company_id, doc, sort, skip, vo.getSize());
        if (!list.isEmpty()) {
            for (String a : list) {
                CardCommodityApiEntity c = new Gson().fromJson(a, CardCommodityApiEntity.class);
                // 创建时间
                if (StringUtil.isLong(c.getCreate_date())) {
                    c.setCreate_date(DateUtil.timestampToString(c.getCreate_date()));
                }
                // 这里需要添加计算奖励积分,若会员类型为客户，则不用计算
                if (entity.getMember_type() == 0) {
                    // 奖励积分默认为0
                    c.setCommission(0);
                    commodityList.add(c);
                    continue;
                }
                // 当前用户下卡可得佣金
                c.setCommission(this.getCommission(c.getCompany_id(), entity, c));
                commodityList.add(c);
            }
        }
        return commodityList;
    }

    /**
     * 当前用户下卡所得佣金
     * @param companyId
     * @param user
     * @param entity
     * @return
     */
    private double getCommission(int companyId, AppUserApiEntity user, CardCommodityApiEntity entity) {
        double commission = 0;
        // 分销员，若分销员没有团队，不在继续向下执行
        if (user.getMember_type() == 1 && !StringUtil.isBlank(user.getTeam_id())) {
            // 找到当前商品，当前团队佣金的分销员佣金
            Bson filter = new Document("commodity_id", entity.getCommodity_id()).append("team_id", user.getTeam_id());
            String info = teamCommodityApiRepository.findCommodity(companyId, filter);
            if (StringUtil.isBlank(info)) return commission;
            TeamCommodityApiEntity teamCommodityApiEntity = new Gson().fromJson(info, TeamCommodityApiEntity.class);
            return teamCommodityApiEntity.getDistribution_total();
        }
        // 团长，若团长没有团队id，也不在向下执行
        if (user.getMember_type() == 2 && !StringUtil.isBlank(user.getTeam_id())) {
            // 找到当前商品，当前团队的团长佣金
            Bson filter = new Document("commodity_id", entity.getCommodity_id()).append("team_id", user.getTeam_id());
            String info = teamCommodityApiRepository.findCommodity(companyId, filter);
            if (StringUtil.isBlank(info)) return commission;
            TeamCommodityApiEntity teamCommodityApiEntity = new Gson().fromJson(info, TeamCommodityApiEntity.class);
            return teamCommodityApiEntity.getTeam_total();
        }
        // 省长,直接去商品的佣金，前提条件是商品的运营者必须有该省长
        if (user.getMember_type() == 3 && CollectionUtils.isNotEmpty(entity.getOperator_list())) {
            for (CardCommodityApiEntity.OperatorEntity info: entity.getOperator_list()) {
                if (info.getUser_id() == user.getUser_id()) {
                    commission = entity.getCommission();
                    break;
                }
            }
        }
        return commission;
    }

    @Override
    public CardCommodityApiEntity findCommodityDetail(CardCommodityApiVO vo) {
        int company_id = vo.getCompany_id();
        // 查询条件拼接
        Document doc = getParam(vo);
        String detail = cardCommodityApiRepository.findCommodityDetail(company_id, doc);
        return StringUtil.isBlank(detail) ? new CardCommodityApiEntity() : new Gson().fromJson(detail, CardCommodityApiEntity.class);
    }

    /**
     * 拼接检索条件
     *
     * @param vo
     * @return
     */
    private Document getParam(CardCommodityApiVO vo) {
        Document doc = new Document("delete_flag", 0);

        // 根据标签进行查询
        if (!StringUtil.isBlank(vo.getLabel_brand_id())) {
            doc.append("label_brand_ids", vo.getLabel_brand_id());
        }

        // 根据商品id进行查询
        if (!StringUtil.isBlank(vo.getCommodity_id())) {
            doc.append("commodity_id", vo.getCommodity_id());
        }

        // 根据银行id进行查询
        if (!StringUtil.isBlank(vo.getBank_id())) {
            doc.append("bank_id", vo.getBank_id());
        }
        return doc;
    }
}
